package com.sxkf.template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxkf.template.constants.OrderConstant;
import com.sxkf.template.dto.EvaluationDto;
import com.sxkf.template.entity.*;
import com.sxkf.template.mapper.*;
import com.sxkf.template.service.CommentLikeService;
import com.sxkf.template.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.vo.request.CommentVo;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-11-22 11:49:23
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {


    @Resource
    private CommentLikeService commentLikeService;
    @Resource
    private StoreEvaluationMapper storeEvaluationMapper;
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;


    @Override
    public Page<Comment> myComment(Integer pageNo, Integer pageSize, Long userId) {
        Page<Comment> page = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Comment>()
                .isNotNull(Comment::getProductId)
                .eq(Comment::getUserId, userId)
        );
        if (page.getRecords().isEmpty()){
            page.getRecords().forEach(item->{
                OrderDetail orderDetail = orderDetailMapper.selectOne(new LambdaQueryWrapper<OrderDetail>()
                        .eq(OrderDetail::getOrderId, item.getOrderId())
                        .eq(OrderDetail::getProductId, item.getProductId()));
                item.setOrderDetail(orderDetail);
            });
        }
        return page;
    }

    @Override
    public String likeById(CommentLike commentLike) {

        if (CheckEmptyUtil.isEmpty(commentLike.getUserId())){
            throw new SxkfException("点赞的用户id为空");
        }

        if (CheckEmptyUtil.isEmpty(commentLike.getCommentId())){
            throw new SxkfException("被点赞评论id为空");
        }

        CommentLike one = commentLikeService.getOne(new LambdaQueryWrapper<CommentLike>()
                .eq(CommentLike::getUserId, commentLike.getUserId())
                .eq(CommentLike::getCommentId, commentLike.getCommentId())
                .eq(CommentLike::getType, commentLike.getType())
        );

        if (CheckEmptyUtil.isEmpty(one)){
            commentLike.setType("1");
            commentLikeService.save(commentLike);
            update(new LambdaUpdateWrapper<Comment>()
                    .setSql("like_count = like_count + 1")
                    .eq(Comment::getId, commentLike.getCommentId())
            );
            return "点赞成功";
        }

        commentLikeService.removeById(one);
        update(new LambdaUpdateWrapper<Comment>()
                .setSql("like_count = like_count - 1")
                .eq(Comment::getId, commentLike.getCommentId())
        );

        return "取消点赞";
    }

    @Override
    public Boolean isLike(String userId, String type, String commentId) {
        CommentLike one = commentLikeService.getOne(new LambdaQueryWrapper<CommentLike>()
                .eq(CommentLike::getUserId, userId)
                .eq(CommentLike::getCommentId, commentId)
                .eq(CommentLike::getType, type)
        );
        return !CheckEmptyUtil.isEmpty(one);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addComment(CommentVo comment) {
        // 保存商品评论
        List<Comment> productComment = comment.getProductComment();
        List<String> productIdList = productComment
                .stream()
                .map(Comment::getProductId)
                .collect(Collectors.toList());
        List<Product> productList = productMapper.selectBatchIds(productIdList);
        Map<String, String> productNameMap = productList.stream().collect(Collectors.toMap(Product::getId, Product::getName));

        productComment.forEach(item -> {
            item.setOrderId(comment.getOrderId());
            item.setProductName(productNameMap.get(item.getProductId()));
        });
        saveBatch(productComment);

        // 保存店铺评论
        StoreEvaluation storeComment = comment.getStoreComment();
        int insert = storeEvaluationMapper.insert(storeComment);
        if (insert > 0) {

            EvaluationDto evaluationDto = storeEvaluationMapper.getRecordSum(storeComment.getStoreId());

            int update = storeMapper.update(null, new LambdaUpdateWrapper<Store>()
                    .set(Store::getUserEvalution, evaluationDto.getEvaluation() / evaluationDto.getCount())
                    .eq(Store::getId, storeComment.getStoreId()));
            if (update > 0) {
                Order order = orderMapper.selectById(comment.getOrderId());
                if (CheckEmptyUtil.isEmpty(order)) {
                    throw new SxkfException("订单不存在");
                }
                // 更新订单状态
                int updateOrder = orderMapper.update(null, new LambdaUpdateWrapper<Order>()
                        .set(Order::getState, OrderConstant.COMMENT)
                        .eq(Order::getId, comment.getOrderId())
                );
                return updateOrder > 0;
            }
        }
        return false;
    }


    @Override
    public Page<Comment> productComment(Integer pageNo, Integer pageSize, String orderId, Long userId) {
        Page<Comment> page = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Comment>().eq(Comment::getUserId, userId).orderByDesc(Comment::getCreateTime));
        if (!page.getRecords().isEmpty()){
            page.getRecords().forEach(item->{
                OrderDetail orderDetail = orderDetailMapper.selectOne(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getProductId, item.getProductId()).eq(OrderDetail::getOrderId, item.getOrderId()));
                item.setOrderDetail(orderDetail);
            });
        }
        return page;
    }
}
